﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace MobileControlGuru.Tools
{
    public class DeepCopyWithExpressionTree
    {
        public static T DeepCopy<T>(T source)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(T), "source");
            MemberInitExpression memberInit = Expression.MemberInit(
                Expression.New(typeof(T)),
                source.GetType().GetProperties()
                  .Where(p => p.CanWrite)
                  .Select(p => Expression.Bind(p, Expression.Property(parameter, p)))
            );
            Expression<Func<T, T>> lambda = Expression.Lambda<Func<T, T>>(memberInit, parameter);
            Func<T, T> compiled = lambda.Compile();
            return compiled(source);
        }
    }
}
